<template>
  <layout>
    <u-navbar :title="navTitle" :background="{ 'background-image': 'linear-gradient(to right, #434AD8, #8E77F5)' }" :border-bottom="false" backIconColor="#fff" titleColor="#fff"></u-navbar>
    
    <u-form
      class="invoice-form"
      :model="form"
      ref="uForm"
      :error-type="['toast']"
      label-width="auto"
      :label-style="labelStyle">
      <u-form-item left-icon="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/main_ic_ttleixing@2x.png" :left-icon-style="iconStyle" label="抬头类型">
        <u-radio-group v-model="form.type" active-color="#FF5673" @change="changeRadio">
          <u-radio name="notCompany" icon-size="29" label-size="25">个人/非企业抬头</u-radio>
          <u-radio name="company" icon-size="29" label-size="25">公司抬头</u-radio>
        </u-radio-group>
      </u-form-item>
      
      <template v-if="form.type === 'company'">
        <u-form-item left-icon="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/main_ic_fptaitou@2x.png" :left-icon-style="iconStyle" label="公司抬头" prop="title">
          <u-input v-model="form.title" type="text" placeholder="请输入公司抬头名称" input-align="right" />
        </u-form-item>
        <u-form-item left-icon="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/main_ic_shuihao@2x.png" :left-icon-style="iconStyle" label="公司税号" prop="number">
          <u-input v-model="form.number" type="text" placeholder="请输入公司税号" input-align="right" />
        </u-form-item>
      </template>
      
      <template v-if="form.type === 'notCompany'">
        <u-form-item left-icon="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/main_ic_fptaitou@2x.png" :left-icon-style="iconStyle" label="个人抬头" prop="title">
          <u-input v-model="form.title" type="text" placeholder="请输入个人抬头名称" input-align="right" />
        </u-form-item>
      </template>
    </u-form>
    
    <view class="h-box">
      <view @click="clickConfirm(0)" class="confirm gray-bgc">保存</view>
      <view @click="clickConfirm(1)" class="confirm pink-bgc">保存并设为默认</view>
    </view>
  </layout>
</template>

<script>
  const db = uniCloud.database()
  const dbCmd = db.command
  
  export default {
    name: 'invoice-title-edit',
    data() {
      return {
        form: {
          type: 'company',
          title: '',
          number: ''
        },
        
        rulesNotCompany: {
          title: [
            {
              required: true,
              message: '请输入个人抬头名称',
              trigger: ['blur', 'change']
            }
          ]
        },
        rulesCompany: {
          title: [
            {
              required: true,
              message: '请输入公司抬头名称',
              trigger: ['blur', 'change']
            }
          ],
          number: [
            {
              required: true,
              message: '请输入公司税号',
              trigger: ['blur', 'change']
            }
          ]
        },
        labelStyle: {
          fontSize: '29rpx'
        },
        iconStyle: {
          width: '36rpx',
          height: '36rpx',
          display: 'flex'
        },
        navTitle: '添加抬头',
        invoiceTitleId: ''
      }
    },
    onLoad(e) {
      this.invoiceTitleId = e?.invoiceTitleId
      this.navTitle = e?.invoiceTitleId ? '编辑抬头' : '添加抬头'
    },
    onReady() {
      this.$refs.uForm.setRules(this.rulesCompany);
      this.getData()
    },
    methods: {
      changeRadio(e) {
        this.form = {
          type: e,
          title: '',
          number: ''
        }
        let rules = e === 'company' ? this.rulesCompany : this.rulesNotCompany
        this.$refs.uForm.setRules(rules);
      },
      
      clickConfirm(type) {
        this.$refs.uForm.validate(async valid => {
          if (valid) {
            uni.showLoading({
              mask: true
            })
            
            try{
              let isDefault = type ? true : false
              
              if (this.invoiceTitleId) {
                if (isDefault) {
                  await db.collection('t3ds-invoice-title')
                  .where({ userId: this.$store.state.userInfo._id, isDefault: true })
                  .update({
                    isDefault: false,
                    updateBy: this.$store.state.userInfo.nickname,
                    updateTime: Date.now()
                  })
                }
                
                let data = Object.assign({
                  userId: this.$store.state.userInfo._id,
                  updateBy: this.$store.state.userInfo.nickname,
                  updateTime: Date.now()
                }, this.form)
                data.isDefault = isDefault
                delete data._id
                await db.collection('t3ds-invoice-title')
                .doc(this.invoiceTitleId)
                .update(data)
              } else {
                let data = Object.assign({
                  isDefault,
                  userId: this.$store.state.userInfo._id,
                  createBy: this.$store.state.userInfo.nickname
                }, this.form)
                await db.collection('t3ds-invoice-title').add(data)
              }
              
              uni.hideLoading()
              uni.showToast({
                title: '保存成功',
                icon: 'none'
              })
              uni.setStorageSync('isUpdate', true)
            }catch(e){
              uni.hideLoading()
              uni.showToast({
                title: '保存失败',
                icon: 'none'
              })
            }
          }
        });
      },
      
      async getData() {
        if (!this.invoiceTitleId) return
        this.form = await this.$dbHelper.getById('t3ds-invoice-title', this.invoiceTitleId, {
          field: {
            _id: true,
            number: true,
            title: true,
            type: true,
            isDefault: true
          }
        })
      }
    }
  }
</script>

<style>
  page {
    background-color: white;
  }
</style>

<style scoped lang="scss">
  .pink-bgc {
    background-color: #FF5673;
  }
  
  .gray-bgc {
    background-color: #CFCFCF;
  }
  
  .invoice-form {
    /deep/ .u-form-item {
      padding-left: 30rpx;
      padding-right: 30rpx;
      font-size: 25rpx !important;
      
      .u-form-item--left__content__icon {
        display: flex;
      }
      
      .u-form-item--right {
        text-align: right;
        
        .u-form-item--right__content__slot {
          justify-content: flex-end;
          
          .u-radio {
            margin-left: 20rpx;
            font-size: 25rpx !important;
            float: right !important;
            
            .u-radio__label:last-child {
              margin-right: 0;
            }
          }
        }
      }
    }
  }

  .confirm {
    width: 330rpx;
    height: 88rpx;
    line-height: 88rpx;
    border-radius: 88rpx;
    font-size: 28rpx;
    text-align: center;
    color: white;
    margin: 0 auto;
    margin-top: 120rpx;
  }
</style>